# -*- coding:utf-8 -*-
# @Time：2020/12/29
"""
通过Python编程完成一个银行ATM机模拟系统，具备如下功能:
(1)登陆验证：用户输入用户名密码登陆，检测用户名是否存在以及用户名密码是否匹配；用户名密码共有三次输入机会，超过三次系统退出。
(2)菜单界面：登陆成功后显示功能操作界面，输入序号选择对应功能。
(3)用户注册：用户可以输入用户名和密码创建自己的账号，并输入电话号码等信息，如果用户名存在则让用户重新输入用户名。注册后免费赠送5000元余额。
(4)账户管理：用户可以随时查看自己的账户余额。用户可以输入其他账户用户名，实现转账功能；转账时用户名必须存在，否则提示异常。用户也可以模拟实现存取款功能。
(5)用户名和密码以及账户信息等必须永久保存。且基于命令行完成，不需要开发GUI界面。
"""
import pymysql
import attr

mysql_conf = {"host": "47.98.254.106", "user": "root", "password": "123456", "database": "Bank_info",
              "port": 3307}


class DbUser:
    def __init__(self, db_info):
        self.__info = db_info
        self.__conn = pymysql.connect(**self.__info)
        self.cursor = self.__conn.cursor()

    # 用户详细信息查询
    def _db_user_info(self) -> object:
        sql = "select * from Bank"
        # 使用 execute（）方法执行 SQL 查询
        self.cursor.execute(sql)
        results = self.cursor.fetchall()
        return results

    # 信息查询(用户是否存在，余额，是否被锁定)
    def db_select(self, key, user):
        sql = 'select {} from Bank where user="{}"'.format(key, user)
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        return result


    # 用户注册
    def db_insert(self, user, passwd, telephone):
        sql = 'insert into Bank(user,passwd,telephone) values ("{}","{}","{}")'.format(user, passwd, telephone)
        self.cursor.execute(sql)
        self.__conn.commit()

    # 更改用户信息(锁定，流水)
    def db_update(self, key, value, user):
        sql = 'update Bank set {}={} where user="{}"'.format(key, value, user)
        self.cursor.execute(sql)
        self.__conn.commit()

    def __del__(self):
        self.__conn.close()
        self.cursor.close()


class BankFun:
    def __init__(self, database, user="deaf", passwd="deaf"):
        self.user = user
        self.passwd = passwd
        self.database = database

    def _print(self):
        dic = {"1": ["register", "注册"], "2": ["login", "登录"], "3": ["check_balance", "查询余额"], "4": ["transfer", "转账"],
               "5": ["save_money", "存钱"], "6": ["traw_money", "取钱"], "7": ["quit", "退出"]}
        # 这个字典用的号很好~
        print("-" * 5 + "请选择对应的功能的序号" + "-" * 5)
        for k in dic.keys():
            print(k, dic.get(k)[1])
        return dic

    def login(self):
        global password
        flag = False  # 登录成功为真
        num = 0
        p = self.passwd

        while True:
            num += 1
            name = self.database.db_select("user", self.user)
            long = len(name)
            if long > 0:
                is_delete = self.database.db_select("is_delete", self.user)
                if int.from_bytes(is_delete[0][0], byteorder='big', signed=True) == 0:
                    passwd = self.database.db_select("passwd", self.user)
                    print(passwd)
                    if num == 3:
                        self.database.db_update("is_delete", 1, self.user)
                        print("密码输入错误三次，{}用户已被锁定,请去人工解锁".format(self.user))
                        break

                    elif p == passwd[0][0]:
                        print("-----账户验证成功-----")
                        flag = True
                        break

                    else:
                        print("密码输入错误{}次,".format(num))
                        p = input("请重新输入密码")

                else:
                    print("-----{}用户已被锁定,请先去人工解锁----".format(self.user))
                    break
            else:
                print("该用户不存在，请输入y，进行注册用户,输入其他将返回登录页面")
                zero = input("请选择是否注册：")
                if zero.strip().lower() == "y":
                    self.register()
                else:
                    print("请确定用户信息再来，谢谢！！！")
                    break
        return flag

    def register(self):
        num = 0
        user_name = self.user
        pass_word = self.passwd
        while True:
            num += 1
            tel = input("请输入联系方式")
            name = self.database.db_select("user", user_name)
            long = len(name)
            if long == 0:
                self.database.db_insert(user_name, pass_word, tel)
                print("---{}用户注册成功,退回首页选择其他功能---".format(user_name))
                print("\n")
                break
            else:
                if num == 3:
                    print("注册失败3次，请稍后注册")
                    break
                else:
                    print("{}用户已存在,注册失败{}次，请重新注册".format(user_name, num))
                    user_name = input("请输入用户名称：----->")
                    pass_word = input("请输入用户密码：----->")

    def check_balance(self):
        tag = self.login()
        if tag:
            check = self.database.db_select("balance", self.user)
            self_money = check[0][0]
            print("{}用户余额：{}".format(username, self_money))
            return self_money

    def transfer(self):
        tag = self.login()
        tran_num = 0
        if tag:
            while tran_num < 3:
                tran_num += 1
                dst_name = input("请输入转账目标用户：")
                name_long = self.database.db_select("user", dst_name)
                long = len(name_long)  # 用户不存在长度为0
                if long == 1:
                    try:
                        money = int(input("请输入转账金额："))
                        src_money = self.database.db_select("balance", self.user)
                        if src_money[0][0] >= money:
                            surplus_money = src_money[0][0] - int(money)
                            self.database.db_update("balance", surplus_money, self.user)  # 源用户剩余金额
                            self.database.db_update("dram_money", money, self.user)  # 源用户转出金额
                            self.database.db_update("save_money", money, dst_name)  # 目标用户转入金额
                            dst_money = self.database.db_select("balance", dst_name)  # 目标用户之前金额
                            self.database.db_update("balance", money + dst_money[0][0], dst_name)  # 目标用户剩余金额
                            print("转账成功,{}用户余额:{}".format(self.user, surplus_money))
                            break
                        else:
                            print("{}用户余额不足，余额为:{}".format(self.user, src_money[0][0]))
                            break
                    except ValueError as error:
                        print("请输入整数")
                        continue

                else:
                    print("{}用户不存在".format(dst_name))
                    if tran_num == 3:
                        print("转账失败3次，请稍后再试")
                        break

    def save_money(self):
        tag = self.login()
        if tag:
            try:
                money = int(input("请输入存入金额："))
                self.database.db_update("save_money", money, self.user)
                src_money = self.database.db_select("balance", self.user)
                total = src_money[0][0] + money
                self.database.db_update("balance", total, self.user)
                print("{}用户余额:{}".format(self.user, total))
            except ValueError as error:
                print("请输入整数")

    def traw_money(self):
        tag = self.login()
        if tag:
            try:
                money = int(input("请输入取款金额："))
                self.database.db_update("dram_money", money, self.user)
                src_money = self.database.db_select("balance", self.user)
                total = src_money[0][0] - money
                self.database.db_update("balance", total, self.user)
                print("{}用户余额:{}".format(self.user, total))
            except ValueError as error:
                print("请输入整数")

    def quit(self):
        tag = False
        print("欢迎下次再来")
        return tag


flag = True
while flag:
    db = DbUser(mysql_conf)
    fun_print = BankFun(db)
    fun_print._print()
    num = input("请输入对应的功能序号：———>")
    if num in ("1", "2", "3", "4", "5", "6"):
        username = input("请输入用户名称：----->")
        password = input("请输入用户密码：----->")
        fun = BankFun(db, user=username, passwd=password)
        # if num in fun_print.keys():
        #     fun_word = fun_print[num][0]
        #     print(fun_word)
        #     b=globals[fun_word]
        #     fun.b()   # 用字典执行类方法报错，识别不了变量 --> 反射考虑下
        if num == "1":
            fun.register()
        elif num == "2":
            fun.login()
        elif num == "3":
            fun.check_balance()
        elif num == "4":
            fun.transfer()
        elif num == "5":
            fun.save_money()
        elif num == "6":
            fun.traw_money()
    elif num == "7":
        flag = fun_print.quit()
    else:
        print("请正确输入")

# 总的来说没有啥问题